<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">缴费记录</h1>
          <p class="mt-1 text-sm text-gray-600">查询学生缴费信息、支付状态、缴费统计等相关事务</p>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="handleRefresh"
            class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新数据
          </button>
          <button
            @click="handleExportReport"
            class="inline-flex items-center px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
          >
            <DocumentArrowDownIcon class="w-4 h-4 mr-2" />
            导出报告
          </button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-5 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <DocumentTextIcon class="h-8 w-8 text-blue-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总记录数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ totalRecords }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CheckCircleIcon class="h-8 w-8 text-green-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">已缴费</p>
            <p class="text-2xl font-semibold text-gray-900">{{ paidRecords }}</p>
            <p class="text-xs text-green-600">{{ paidRate }}%</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ClockIcon class="h-8 w-8 text-yellow-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">待缴费</p>
            <p class="text-2xl font-semibold text-gray-900">{{ pendingRecords }}</p>
            <p class="text-xs text-yellow-600">{{ pendingRate }}%</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ExclamationTriangleIcon class="h-8 w-8 text-red-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">逾期未缴</p>
            <p class="text-2xl font-semibold text-gray-900">{{ overdueRecords }}</p>
            <p class="text-xs text-red-600">需要关注</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CurrencyDollarIcon class="h-8 w-8 text-purple-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总金额</p>
            <p class="text-2xl font-semibold text-gray-900">¥{{ formatMoney(totalAmount) }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 缴费趋势图表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <h2 class="text-lg font-medium text-gray-900 mb-4">缴费趋势</h2>
      <div ref="chartContainer" class="h-64"></div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-6 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">学号/姓名</label>
          <input
            v-model="searchForm.keyword"
            type="text"
            placeholder="请输入学号或姓名"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">缴费项目</label>
          <Listbox v-model="searchForm.paymentItem">
            <div class="relative">
              <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <span class="block truncate">{{ searchForm.paymentItem || '请选择项目' }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>
              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                  <ListboxOption value="" class="relative cursor-default select-none py-2 pl-10 pr-4 text-gray-900 hover:bg-blue-100">
                    <span class="block truncate font-normal">全部项目</span>
                  </ListboxOption>
                  <ListboxOption
                    v-for="item in paymentItems"
                    :key="item"
                    :value="item"
                    v-slot="{ active, selected }"
                    class="relative cursor-default select-none py-2 pl-10 pr-4"
                    :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                  >
                    <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                      {{ item }}
                    </span>
                    <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                      <CheckIcon class="h-5 w-5" aria-hidden="true" />
                    </span>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">支付状态</label>
          <select
            v-model="searchForm.paymentStatus"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部状态</option>
            <option value="已缴费">已缴费</option>
            <option value="待缴费">待缴费</option>
            <option value="逾期未缴">逾期未缴</option>
            <option value="部分缴费">部分缴费</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">支付方式</label>
          <select
            v-model="searchForm.paymentMethod"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部方式</option>
            <option value="在线支付">在线支付</option>
            <option value="银行转账">银行转账</option>
            <option value="现金缴费">现金缴费</option>
            <option value="支付宝">支付宝</option>
            <option value="微信支付">微信支付</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">缴费时间</label>
          <input
            v-model="searchForm.paymentDate"
            type="date"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
        </div>
        <div class="flex items-end gap-2">
          <button
            @click="handleSearch"
            class="flex-1 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <MagnifyingGlassIcon class="w-4 h-4 mr-2 inline" />
            搜索
          </button>
          <button
            @click="handleReset"
            class="px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
          >
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 缴费记录列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">缴费记录列表</h2>
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-500">共 {{ filteredRecords.length }} 条记录</span>
            <div class="flex items-center gap-2">
              <button
                @click="handleBatchConfirm"
                :disabled="selectedRecords.length === 0"
                class="px-3 py-1.5 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <CheckCircleIcon class="w-4 h-4 mr-1 inline" />
                批量确认
              </button>
              <button
                @click="handleExport"
                class="px-3 py-1.5 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
              >
                <ArrowDownTrayIcon class="w-4 h-4 mr-1 inline" />
                导出
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left">
                <input
                  type="checkbox"
                  :checked="selectedRecords.length === filteredRecords.length && filteredRecords.length > 0"
                  @change="handleSelectAll"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">缴费项目</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">缴费金额</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">支付状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">支付方式</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">缴费时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">交易流水号</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="record in paginatedRecords" :key="record.id" class="hover:bg-gray-50">
              <td class="px-6 py-4">
                <input
                  type="checkbox"
                  :value="record.id"
                  v-model="selectedRecords"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-10 w-10">
                    <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                      <UserIcon class="h-6 w-6 text-gray-600" />
                    </div>
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ record.studentName }}</div>
                    <div class="text-sm text-gray-500">{{ record.studentId }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">{{ record.paymentItem }}</div>
                <div class="text-sm text-gray-500">{{ record.itemCode }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">¥{{ formatMoney(record.amount) }}</div>
                <div v-if="record.paidAmount !== record.amount" class="text-xs text-gray-500">
                  已缴: ¥{{ formatMoney(record.paidAmount) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="getStatusClass(record.paymentStatus)"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ record.paymentStatus }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ record.paymentMethod || '-' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ record.paymentTime || '-' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ record.transactionId || '-' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    @click="handleViewDetails(record)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                    title="查看详情"
                  >
                    <EyeIcon class="w-4 h-4" />
                  </button>
                  <button
                    v-if="record.paymentStatus === '待缴费'"
                    @click="handleConfirmPayment(record)"
                    class="text-green-600 hover:text-green-900 transition-colors"
                    title="确认缴费"
                  >
                    <CheckCircleIcon class="w-4 h-4" />
                  </button>
                  <button
                    v-if="record.paymentStatus === '已缴费'"
                    @click="handleRefund(record)"
                    class="text-red-600 hover:text-red-900 transition-colors"
                    title="退费"
                  >
                    <ArrowUturnLeftIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleEdit(record)"
                    class="text-yellow-600 hover:text-yellow-900 transition-colors"
                    title="编辑"
                  >
                    <PencilIcon class="w-4 h-4" />
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredRecords.length) }} 条，共 {{ filteredRecords.length }} 条
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm font-medium text-gray-700">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 记录详情弹窗 -->
    <Dialog :open="showDetailsModal" @close="showDetailsModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            缴费记录详情
          </DialogTitle>
          
          <div v-if="selectedRecord" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">学号</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.studentId }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.studentName }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">缴费项目</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.paymentItem }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">项目编码</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.itemCode }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">应缴金额</label>
                <p class="text-sm text-gray-900">¥{{ formatMoney(selectedRecord.amount) }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">已缴金额</label>
                <p class="text-sm text-gray-900">¥{{ formatMoney(selectedRecord.paidAmount) }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">支付状态</label>
                <span
                  :class="getStatusClass(selectedRecord.paymentStatus)"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ selectedRecord.paymentStatus }}
                </span>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">支付方式</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.paymentMethod || '-' }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">缴费时间</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.paymentTime || '-' }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">交易流水号</label>
                <p class="text-sm text-gray-900">{{ selectedRecord.transactionId || '-' }}</p>
              </div>
            </div>
            
            <div v-if="selectedRecord.remark">
              <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
              <div class="bg-gray-50 rounded-lg p-3">
                <p class="text-sm text-gray-900">{{ selectedRecord.remark }}</p>
              </div>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showDetailsModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 确认缴费弹窗 -->
    <Dialog :open="showConfirmModal" @close="showConfirmModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-md rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            确认缴费
          </DialogTitle>
          
          <div v-if="selectedRecord" class="space-y-4">
            <div class="bg-blue-50 rounded-lg p-4">
              <p class="text-sm text-blue-800">
                确认 <span class="font-medium">{{ selectedRecord.studentName }}</span> 
                的 <span class="font-medium">{{ selectedRecord.paymentItem }}</span> 
                缴费 <span class="font-medium">¥{{ formatMoney(selectedRecord.amount) }}</span> 吗？
              </p>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">支付方式</label>
              <select
                v-model="confirmForm.paymentMethod"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="在线支付">在线支付</option>
                <option value="银行转账">银行转账</option>
                <option value="现金缴费">现金缴费</option>
                <option value="支付宝">支付宝</option>
                <option value="微信支付">微信支付</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">交易流水号</label>
              <input
                v-model="confirmForm.transactionId"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                placeholder="请输入交易流水号"
              />
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">备注</label>
              <textarea
                v-model="confirmForm.remark"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                placeholder="请输入备注信息"
              ></textarea>
            </div>
          </div>
          
          <div class="flex justify-end gap-3 pt-4">
            <button
              @click="showConfirmModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              取消
            </button>
            <button
              @click="handleConfirmSubmit"
              class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
            >
              确认缴费
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useAppStore } from '../../stores/app'
import * as echarts from 'echarts'
import {
  Dialog,
  DialogPanel,
  DialogTitle,
  Listbox,
  ListboxButton,
  ListboxOptions,
  ListboxOption
} from '@headlessui/vue'
import {
  ArrowPathIcon,
  DocumentArrowDownIcon,
  DocumentTextIcon,
  CheckCircleIcon,
  ClockIcon,
  ExclamationTriangleIcon,
  CurrencyDollarIcon,
  MagnifyingGlassIcon,
  ArrowDownTrayIcon,
  UserIcon,
  EyeIcon,
  PencilIcon,
  ArrowUturnLeftIcon,
  ChevronUpDownIcon,
  CheckIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const searchForm = ref({
  keyword: '',
  paymentItem: '',
  paymentStatus: '',
  paymentMethod: '',
  paymentDate: ''
})

const showDetailsModal = ref(false)
const showConfirmModal = ref(false)
const selectedRecords = ref([])
const selectedRecord = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const chartContainer = ref(null)

const confirmForm = ref({
  paymentMethod: '在线支付',
  transactionId: '',
  remark: ''
})

// 模拟数据
const paymentRecords = ref([
  {
    id: 1,
    studentId: '2024001',
    studentName: '张三',
    paymentItem: '学费',
    itemCode: 'TUITION_2024',
    amount: 5000,
    paidAmount: 5000,
    paymentStatus: '已缴费',
    paymentMethod: '在线支付',
    paymentTime: '2024-08-25 14:30:00',
    transactionId: 'TXN202408251430001',
    remark: '按时缴费'
  },
  {
    id: 2,
    studentId: '2024002',
    studentName: '李四',
    paymentItem: '住宿费',
    itemCode: 'DORM_2024',
    amount: 1200,
    paidAmount: 1200,
    paymentStatus: '已缴费',
    paymentMethod: '支付宝',
    paymentTime: '2024-08-26 09:15:00',
    transactionId: 'ALI202408260915001',
    remark: ''
  },
  {
    id: 3,
    studentId: '2024003',
    studentName: '王五',
    paymentItem: '学费',
    itemCode: 'TUITION_2024',
    amount: 5000,
    paidAmount: 0,
    paymentStatus: '待缴费',
    paymentMethod: null,
    paymentTime: null,
    transactionId: null,
    remark: ''
  },
  {
    id: 4,
    studentId: '2024004',
    studentName: '赵六',
    paymentItem: '教材费',
    itemCode: 'BOOK_2024',
    amount: 300,
    paidAmount: 150,
    paymentStatus: '部分缴费',
    paymentMethod: '微信支付',
    paymentTime: '2024-08-27 16:45:00',
    transactionId: 'WX202408271645001',
    remark: '分期缴费'
  },
  {
    id: 5,
    studentId: '2024005',
    studentName: '钱七',
    paymentItem: '学费',
    itemCode: 'TUITION_2024',
    amount: 5000,
    paidAmount: 0,
    paymentStatus: '逾期未缴',
    paymentMethod: null,
    paymentTime: null,
    transactionId: null,
    remark: '需要催缴'
  }
])

// 计算属性
const paymentItems = computed(() => {
  return [...new Set(paymentRecords.value.map(r => r.paymentItem))]
})

const filteredRecords = computed(() => {
  let result = paymentRecords.value
  
  if (searchForm.value.keyword) {
    result = result.filter(record => 
      record.studentName.includes(searchForm.value.keyword) ||
      record.studentId.includes(searchForm.value.keyword)
    )
  }
  
  if (searchForm.value.paymentItem) {
    result = result.filter(record => record.paymentItem === searchForm.value.paymentItem)
  }
  
  if (searchForm.value.paymentStatus) {
    result = result.filter(record => record.paymentStatus === searchForm.value.paymentStatus)
  }
  
  if (searchForm.value.paymentMethod) {
    result = result.filter(record => record.paymentMethod === searchForm.value.paymentMethod)
  }
  
  if (searchForm.value.paymentDate) {
    result = result.filter(record => {
      if (!record.paymentTime) return false
      const paymentDate = record.paymentTime.split(' ')[0]
      return paymentDate === searchForm.value.paymentDate
    })
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredRecords.value.length / pageSize.value)
})

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

const totalRecords = computed(() => paymentRecords.value.length)
const paidRecords = computed(() => paymentRecords.value.filter(r => r.paymentStatus === '已缴费').length)
const pendingRecords = computed(() => paymentRecords.value.filter(r => r.paymentStatus === '待缴费').length)
const overdueRecords = computed(() => paymentRecords.value.filter(r => r.paymentStatus === '逾期未缴').length)

const paidRate = computed(() => {
  return totalRecords.value > 0 ? Math.round((paidRecords.value / totalRecords.value) * 100) : 0
})

const pendingRate = computed(() => {
  return totalRecords.value > 0 ? Math.round((pendingRecords.value / totalRecords.value) * 100) : 0
})

const totalAmount = computed(() => {
  return paymentRecords.value.reduce((sum, record) => sum + record.paidAmount, 0)
})

// 方法
const formatMoney = (amount) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const getStatusClass = (status) => {
  switch (status) {
    case '已缴费':
      return 'bg-green-100 text-green-800'
    case '待缴费':
      return 'bg-yellow-100 text-yellow-800'
    case '逾期未缴':
      return 'bg-red-100 text-red-800'
    case '部分缴费':
      return 'bg-blue-100 text-blue-800'
    default:
      return 'bg-gray-100 text-gray-800'
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.value = {
    keyword: '',
    paymentItem: '',
    paymentStatus: '',
    paymentMethod: '',
    paymentDate: ''
  }
  currentPage.value = 1
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedRecords.value = filteredRecords.value.map(record => record.id)
  } else {
    selectedRecords.value = []
  }
}

const handleViewDetails = (record) => {
  selectedRecord.value = record
  showDetailsModal.value = true
}

const handleConfirmPayment = (record) => {
  selectedRecord.value = record
  confirmForm.value = {
    paymentMethod: '在线支付',
    transactionId: '',
    remark: ''
  }
  showConfirmModal.value = true
}

const handleConfirmSubmit = async () => {
  if (!selectedRecord.value) return
  
  const index = paymentRecords.value.findIndex(r => r.id === selectedRecord.value.id)
  if (index > -1) {
    paymentRecords.value[index] = {
      ...paymentRecords.value[index],
      paymentStatus: '已缴费',
      paidAmount: paymentRecords.value[index].amount,
      paymentMethod: confirmForm.value.paymentMethod,
      paymentTime: new Date().toLocaleString('zh-CN'),
      transactionId: confirmForm.value.transactionId || `TXN${Date.now()}`,
      remark: confirmForm.value.remark
    }
  }
  
  showConfirmModal.value = false
  appStore.showNotification(`${selectedRecord.value.studentName} 缴费确认成功`, 'success')
}

const handleRefund = async (record) => {
  if (confirm(`确定要为 ${record.studentName} 的 ${record.paymentItem} 办理退费吗？`)) {
    const index = paymentRecords.value.findIndex(r => r.id === record.id)
    if (index > -1) {
      paymentRecords.value[index].paymentStatus = '已退费'
      paymentRecords.value[index].paidAmount = 0
    }
    appStore.showNotification('退费处理成功', 'success')
  }
}

const handleEdit = (record) => {
  appStore.showNotification('编辑功能开发中', 'info')
}

const handleBatchConfirm = async () => {
  if (selectedRecords.value.length === 0) return
  
  selectedRecords.value.forEach(recordId => {
    const index = paymentRecords.value.findIndex(r => r.id === recordId)
    if (index > -1 && paymentRecords.value[index].paymentStatus === '待缴费') {
      paymentRecords.value[index] = {
        ...paymentRecords.value[index],
        paymentStatus: '已缴费',
        paidAmount: paymentRecords.value[index].amount,
        paymentMethod: '批量确认',
        paymentTime: new Date().toLocaleString('zh-CN'),
        transactionId: `BATCH${Date.now()}`
      }
    }
  })
  
  selectedRecords.value = []
  appStore.showNotification('批量确认成功', 'success')
}

const handleRefresh = () => {
  appStore.showNotification('数据已刷新', 'success')
}

const handleExport = () => {
  const csvContent = [
    ['学号', '姓名', '缴费项目', '项目编码', '应缴金额', '已缴金额', '支付状态', '支付方式', '缴费时间', '交易流水号', '备注'],
    ...filteredRecords.value.map(record => [
      record.studentId,
      record.studentName,
      record.paymentItem,
      record.itemCode,
      record.amount,
      record.paidAmount,
      record.paymentStatus,
      record.paymentMethod || '',
      record.paymentTime || '',
      record.transactionId || '',
      record.remark || ''
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `缴费记录_${new Date().toISOString().split('T')[0]}.csv`
  link.click()
  
  appStore.showNotification('导出成功', 'success')
}

const handleExportReport = () => {
  appStore.showNotification('缴费报告导出功能开发中', 'info')
}

const initChart = () => {
  if (!chartContainer.value) return
  
  const chart = echarts.init(chartContainer.value)
  
  const option = {
    title: {
      text: '缴费趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['缴费金额', '缴费人数'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['8/20', '8/21', '8/22', '8/23', '8/24', '8/25', '8/26', '8/27', '8/28']
    },
    yAxis: [
      {
        type: 'value',
        name: '金额(万元)',
        position: 'left',
        axisLabel: {
          formatter: '{value}万'
        }
      },
      {
        type: 'value',
        name: '人数',
        position: 'right',
        axisLabel: {
          formatter: '{value}人'
        }
      }
    ],
    series: [
      {
        name: '缴费金额',
        type: 'bar',
        yAxisIndex: 0,
        data: [50, 80, 120, 90, 150, 200, 180, 160, 140],
        itemStyle: {
          color: '#3B82F6'
        }
      },
      {
        name: '缴费人数',
        type: 'line',
        yAxisIndex: 1,
        data: [20, 35, 50, 40, 65, 85, 75, 70, 60],
        smooth: true,
        itemStyle: {
          color: '#10B981'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 生命周期
onMounted(async () => {
  await nextTick()
  initChart()
})
</script>